package PartC;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoServer{
	
	public static void main(String args [])throws Exception{
		
		
		ServerSocket welcomeSocket = new ServerSocket(6789);
		boolean listening = true;
		
		// Pick a thread model ...
		boolean cachedThreadPool = true;
		boolean fixedThreadPool = false;
		boolean singleThreadPool = false;
		
		if (cachedThreadPool) {
			// Many threads will be created and all requests handled.
		    ExecutorService executor = Executors.newCachedThreadPool();
		    while(listening){
		    	Request request = new Request(welcomeSocket.accept());
		    	executor.execute(request);
		    }
		}
		if (fixedThreadPool){
			// With a fixed thread pool of 2, more than two connections will
			// be made, but only the first 2 will be handled and responded to.
			// Any requests that were not handled will be handled when one of
			// threads becomes available.
			ExecutorService executor = Executors.newFixedThreadPool(2);
			while (listening) {
			    Request request = new Request(welcomeSocket.accept());
			    executor.execute(request);
			}
		}
		if (singleThreadPool) {
			// With a single thread pool, only the first connection will be dealt with.
			// As with the fixed thread pool, waiting requests will be handled when the
			// thread becomes available
		    ExecutorService executor = Executors.newSingleThreadExecutor();
			while (listening) {
			    Request request = new Request(welcomeSocket.accept());
			    executor.execute(request);
			}
		}
		
		welcomeSocket.close();

	}

}
